package org.aplombh.java.utils.multiThread.juc.safe;

public class BuyTicket implements Runnable{

    private int ticketNums = 10;
    private boolean flat = true;

    @Override
    public void run() {
        while (flat){
            buy();
        }
    }

    // Synchronize method, lock this。
    private synchronized void buy(){
        if (ticketNums <= 0){
            flat = false;
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " get " + ticketNums--+"th ticket.");
    }

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"one").start();
        new Thread(buyTicket,"two").start();
        new Thread(buyTicket,"three").start();
    }
}
